package com.major.crowd.controller;

import com.major.crowd.api.MysqlRemoteService;
import com.major.crowd.config.OSSProperties;
import com.major.crowd.constant.CrowdConstant;
import com.major.crowd.util.CrowdUtil;
import com.major.crowd.util.ResultEntity;
import com.major.crowd.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ProjectConsumerController {

    @Autowired
    private OSSProperties ossProperties;
    @Autowired
    private MysqlRemoteService mysqlRemoteService;

    /**
     * 调用 查询项目详情 的接口
     * @param projectId
     * @param model
     * @return
     */
    @RequestMapping("/get/project/detail/{projectId}")
    public String getProjectDetail(
            @PathVariable("projectId")Integer projectId,
            Model model
    ){
        ResultEntity<DetailProjectVO> resultEntity = mysqlRemoteService.getDetailProjectVORemote(projectId);

        if (ResultEntity.SUCCESS.equals(resultEntity.getResult())){
            DetailProjectVO detailProjectVO = resultEntity.getData();
            model.addAttribute("detailProjectVO",detailProjectVO);
        }
        return "project-detail";
    }

    /**
     * 确认页面
     * @param session
     * @param memberConfirmInfoVO
     * @param modelMap
     * @return
     */
    @RequestMapping("/create/confirm")
    public String saveConfirm(
            HttpSession session,
            MemberConfirmInfoVO memberConfirmInfoVO,
            ModelMap modelMap
    ){
        // 取出projectVO对象
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
        // 错误情况
        if (projectVO == null){
            throw new RuntimeException(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
        }
        // 将确认信息设置到projectVO对象中
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        // 从session域中取出会员,得到id
        MemberLoginVO memberLoginVO = (MemberLoginVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        Integer memberId = memberLoginVO.getId();

        // 调用远程mysql接口，保存对象
        ResultEntity<String> saveResultEntity =  mysqlRemoteService.saveProjectVORemote(projectVO,memberId);

        // 判断 保存是否成功
        String result = saveResultEntity.getResult();
        if (ResultEntity.FAILED.equals(result)){                // 失败
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,saveResultEntity.getMessage());
            return "project-confirm";
        }

        // session域中临时的projectVO对象移除
        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        // 成功
        return "redirect:http://localhost/project/create/success";
    }

    /**
     * 回报信息页面
     * @param returnVO
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(
            ReturnVO returnVO,
            HttpSession session
    ){
        try {
            // 读取session域中之前缓存的ProjectVO对象
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

            // 判断一下
            if (projectVO == null){
                return ResultEntity.failed(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
            }

            // 获取projectVO信息
            List<ReturnVO> returnVOList = projectVO.getReturnVOList();

            if (returnVOList == null || returnVOList.size() == 0){
                returnVOList = new ArrayList<>();
                // 放回去
                projectVO.setReturnVOList(returnVOList);
            }

            // 将收集了表单数据的returnVO对象存入集合
            returnVOList.add(returnVO);

            // 存入session域
            session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT,projectVO);

            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    /**
     * 回报信息，图片
     * @param returnPicture
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/create/upload/return/picture.json")
    public ResultEntity<String> upLoadReturnPicture(
            @RequestParam("returnPicture") MultipartFile returnPicture
    ) throws IOException {

        // 上传图片
        ResultEntity<String> upLoadReturnPictureResultEntity = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                returnPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                returnPicture.getOriginalFilename());
        // 返回上传结果
        return upLoadReturnPictureResultEntity;
    }

    /**
     * 发起项目，收集项目基本信息
     *
     * @param projectVO         接收除了图片外的普通数据
     * @param headerPicture     接收头图
     * @param detailPictureList 接收详情图
     * @param session           将 projectVO对象 存入Session域
     * @param modelMap          操作失败后，返回上一个页面，携带提示消息
     * @return
     */
    @RequestMapping("/create/project/information")
    public String saveProjectBasicInfo(
            ProjectVO projectVO,
            MultipartFile headerPicture,
            List<MultipartFile> detailPictureList,
            HttpSession session,
            ModelMap modelMap
    ) throws IOException {

        /********************* 上传头图 ***************************/
        boolean isHeaderEmpty = headerPicture.isEmpty();

        if (isHeaderEmpty) {
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_EMPTY);
            return "project-launch";
        }

        // 判断用户是否上传了头图，上传到oss
        ResultEntity<String> uploadHeaderPicResult = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                headerPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                headerPicture.getOriginalFilename());
        String result = uploadHeaderPicResult.getResult();

        if (ResultEntity.SUCCESS.equals(result)) {           // 判断成功上传到服务器
            String headerPicPath = uploadHeaderPicResult.getData();
            // 存入VO对象
            projectVO.setHeaderPicturePath(headerPicPath);
        } else {
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
            return "project-launch";
        }

        /********************* 上传详情图片 ***************************/
        List<String> detailPicPathList = new ArrayList<>();

        // 检查list是否有效
        if (detailPictureList == null || detailPictureList.size() == 0) {            // 详情图集合为空，返回
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
            return "project-launch";
        }

        // 遍历detailPicList集合
        for (MultipartFile detailPic : detailPictureList) {

            if (detailPic.isEmpty()) {           // 单个详情图为空，返回
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
                return "project-launch";
            }

            // 上传到oss
            ResultEntity<String> detailUploadResultEntity = CrowdUtil.uploadFileToOss(
                    ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    detailPic.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    detailPic.getOriginalFilename());

            // 检查上传结果
            String detailUploadResult = detailUploadResultEntity.getResult();
            if (ResultEntity.SUCCESS.equals(detailUploadResult)) {           // 成功
                String detailPicPath = detailUploadResultEntity.getData();
                detailPicPathList.add(detailPicPath);                       // 存入集合
            }else {
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
                return "project-launch";
            }

        }
        // 存入projectVO对象
        projectVO.setDetailPicturePathList(detailPicPathList);

        /******************* 后续操作 ***********************/
        // 将projectVO对象存入Session域
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);
        // 以完整的路径
        return "redirect:http://localhost/project/return/info/page";
    }
}
